﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Xml.Linq;

namespace Twi.COMMON.WPF
{
    [ValueConversion(typeof(string), typeof(string))]
    public class XElementExpressionConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string expr = parameter.ToString();
            XElement dataContext = value as XElement;

            //表达式中存在的XElement节点
            var expr_xelementList = expr.ToString().Split(new string[] { "Element[", "].Value" }, StringSplitOptions.RemoveEmptyEntries)
                .Where(x => expr.Contains(string.Format("Element[{0}].Value", x)));

            foreach (var x in expr_xelementList) 
            {
                expr = expr.Replace(string.Format("Element[{0}].Value", x), dataContext.Element(x).Value);
            }
            return expr;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
